package cn.wawi.controller;

import java.beans.PropertyEditorSupport;
import java.lang.reflect.ParameterizedType;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import cn.wawi.common.Json;
import cn.wawi.common.StringEscapeEditor;
import cn.wawi.common.easyui.DataGrid;
import cn.wawi.dao.DaoSupport;
import cn.wawi.dao.data.CurriculumDao;
import cn.wawi.dao.data.CurriculumTypeDao;
import cn.wawi.dao.data.EnterpriseDao;
import cn.wawi.dao.data.GradeDao;
import cn.wawi.dao.data.PostDao;
import cn.wawi.dao.data.QuestionBankDao;
import cn.wawi.dao.data.QuestionOptionDao;
import cn.wawi.dao.data.QuestionTypeDao;
import cn.wawi.dao.data.RecruitmentDao;
import cn.wawi.dao.data.SkillCardDao;
import cn.wawi.dao.data.SkillDao;
import cn.wawi.dao.data.TradeDao;
import cn.wawi.dao.sys.DepartmentDao;
import cn.wawi.dao.sys.DictitemDao;
import cn.wawi.dao.sys.LogDao;
import cn.wawi.dao.sys.PrivilegeDao;
import cn.wawi.dao.sys.RoleDao;
import cn.wawi.dao.sys.UserDao;
import cn.wawi.entity.data.Curriculum;
import cn.wawi.entity.data.CurriculumType;
import cn.wawi.entity.data.Enterprise;
import cn.wawi.entity.data.Grade;
import cn.wawi.entity.data.Post;
import cn.wawi.entity.data.QuestionBank;
import cn.wawi.entity.data.QuestionOption;
import cn.wawi.entity.data.QuestionType;
import cn.wawi.entity.data.Recruitment;
import cn.wawi.entity.data.Skill;
import cn.wawi.entity.data.SkillCard;
import cn.wawi.entity.data.Trade;
import cn.wawi.entity.sys.Department;
import cn.wawi.entity.sys.Dictitem;
import cn.wawi.entity.sys.Log;
import cn.wawi.entity.sys.Privilege;
import cn.wawi.entity.sys.Role;
import cn.wawi.entity.sys.User;
import cn.wawi.utils.DateUtil;
import cn.wawi.utils.QueryUtil;
import com.github.pagehelper.PageInfo;
import com.liang.kit.ReflectUtil;

/**
 * <--------------基础控制器-------------->
 * @author 龚亮
 * @date 2015-05-25 14:49:35
 */
@Transactional
public abstract class BaseController<T> {
	
	@Resource
	private DaoSupport dao;
	private String mapperName;
	private Class<T> clazz;
	@Resource
	protected UserDao<User> userDao;
	@Resource
	protected RoleDao<Role> roleDao;
	@Resource
	protected DepartmentDao<Department> departmentDao;
	@Resource
	protected PrivilegeDao<Privilege> privilegeDao;
	@Resource
	protected LogDao<Log> logDao;
	@Resource
	protected DictitemDao<Dictitem> dictitemDao;
	
	@Resource
	protected GradeDao<Grade> gradeDao;
	@Resource
	protected PostDao<Post> postDao;
	@Resource
	protected TradeDao<Trade> tradeDao;
	@Resource
	protected SkillDao<Skill> skillDao;
	@Resource
	protected QuestionBankDao<QuestionBank> questionBankDao;
	@Resource
	protected QuestionTypeDao<QuestionType> questionTypeDao;
	@Resource
	protected QuestionOptionDao<QuestionOption> questionOptionDao;
	@Resource
	protected EnterpriseDao<Enterprise> enterpriseDao;
	@Resource
	protected CurriculumTypeDao<CurriculumType> curriculumTypeDao;
	@Resource
	protected CurriculumDao<Curriculum> curriculumDao;
	@Resource
	protected SkillCardDao<SkillCard> skillCardDao;
	@Resource
	protected RecruitmentDao<Recruitment> recruitmentDao;
	
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		// String类型转换，将所有传递进来的String进行HTML编码，防止XSS攻击、sql注入
		binder.registerCustomEditor(String.class, new StringEscapeEditor(true,false,false));
		
		// Date 类型转换
		binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
			@Override
			public void setAsText(String text) {
				setValue(DateUtil.parseDate(text));
			}
		});
		
		// Timestamp 类型转换
		binder.registerCustomEditor(Timestamp.class, new PropertyEditorSupport() {
			@Override
			public void setAsText(String text) {
				Date date = DateUtil.parseDate(text);
				setValue(date==null?null:new Timestamp(date.getTime()));
			}
		});
	}
	@ModelAttribute
	public void init(HttpServletRequest request){

	}
	@SuppressWarnings("all")
	public BaseController(){
		try {
			ParameterizedType pt=(ParameterizedType) this.getClass().getGenericSuperclass();
			clazz=(Class<T>) pt.getActualTypeArguments()[0];
			mapperName=clazz.getName().replaceAll("entity", "dao")+"Dao";
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException();
		}
	}
	/**
	 * 查询所有(不分页)
	 * @return DataGrid
	 */
	public DataGrid findAll(HttpServletRequest request){
		List<T> list=dao.findAll(mapperName, QueryUtil.setNoPage(request));
		DataGrid dataGrid=new DataGrid(list,list.size()+0L);
		return dataGrid;
	}

	/**
	 * 分页查询
	 * @return DataGrid
	 */
	public DataGrid findAllByPage(HttpServletRequest request){
		List<T> list=dao.findAll(mapperName, QueryUtil.setPage(request));
		PageInfo<T> pages = new PageInfo<T>(list);
		DataGrid dataGrid=new DataGrid(pages.getList(),pages.getTotal());
		return dataGrid;
	}
	/**
	 * 分页查询自定义分页
	 * @param pageIndex 第几页
	 * @param pageSize  每页显示几条数据
	 * @return DataGrid
	 */
	public DataGrid findAllByPage(HttpServletRequest request,int pageIndex,int pageSize){
		List<T> list=dao.findAll(mapperName, QueryUtil.setPage(request,pageIndex,pageSize));
		PageInfo<T> pages = new PageInfo<T>(list);
		DataGrid dataGrid=new DataGrid(pages.getList(),pages.getTotal());
		return dataGrid;
	}
	/**
	 *根据一组id删除
	 */
	@ResponseBody
	@RequestMapping(value="/delete/{ids}",method=RequestMethod.DELETE)
	public Json delete(@PathVariable String ids){
	    dao.updateBatch(mapperName, ids);
		return new Json("delete", "根据id批量删除!");
	}
	/**
	 *根据一组id删除
	 */
	@ResponseBody
	@RequestMapping(value="/deleteBatch/{ids}",method=RequestMethod.DELETE)
	public Json deleteBatch(@PathVariable String ids){
	    dao.deleteBatch(mapperName, ids);
		return new Json("deleteBatch", "根据id批量删除!");
	}
	
	@ResponseBody
	@RequestMapping(value="/update",method=RequestMethod.POST)
	public Json update(HttpServletRequest request,T t){
		String parentId=request.getParameter("_parentId");
		if(parentId!=null&&!"".equals(parentId.trim())){
			ReflectUtil.setFieldValue(t, "_parentId", Long.parseLong(parentId));
		}
		dao.update(mapperName,t);
		return new Json("save", "更新信息!");
	}

	@ResponseBody
	@RequestMapping(value="/save",method=RequestMethod.POST)
	public Json save(HttpServletRequest request,T t){
		String parentId=request.getParameter("_parentId");
		if(parentId!=null&&!"".equals(parentId.trim())){
			ReflectUtil.setFieldValue(t, "_parentId", Long.parseLong(parentId));
		}
		dao.save(mapperName,t);
		return new Json("save", "添加信息!");
	}
	@RequestMapping(value="/main",method=RequestMethod.GET)
	public String main() {
		String pName=clazz.getPackage().getName();
		String main=pName.substring(pName.lastIndexOf(".")+1)+"/"+clazz.getSimpleName()+"/main";
		return main;
	}
	
	@ResponseBody
	@RequestMapping(value = "/getCombo", method = RequestMethod.GET)
	public List<T> getCombo() {
		List<T> list = dao.findAll(mapperName, null);
		return list;
	}
	
	@ResponseBody
	@RequestMapping(value="/all",method={RequestMethod.GET,RequestMethod.POST})
	public List<T> queryAll(HttpServletRequest request){
		List<T> list=dao.findAll(mapperName, QueryUtil.setNoPage(request));
		return list;
	}
}